package com.portal.framework.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//import net.sourceforge.pinyin4j.PinyinHelper;
//import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
//import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
//import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
//import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import com.portal.framework.exception.AppException;

/**
 *  常用工具方法类
 * 
 * @author 卢烁波
 * @date 2007-3-10
 */
public class StringUtils {

	public static int indexOfTimes(String str, String searchStr, int times) {
		int maxTimes = 100000;
		if (times > maxTimes) {
			throw new IllegalArgumentException("max times is " + maxTimes);
		}
		if (str == null || searchStr == null || times <= 0 || times > maxTimes) {
			return -1;
		}
		int result = 0;
		for (int i = times; i > 0; i--) {
			result = str.indexOf(searchStr, result + 1);
			if (result == -1) {
				break;
			}
		}

		return result;
	}

	/**
	 * 是否有文字,空白不算文字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean hasText(String str) {
		int strLen;
		if (str == null || (strLen = str.length()) == 0) {
			return false;
		}
		for (int i = 0; i < strLen; i++) {
			if (!Character.isWhitespace(str.charAt(i))) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 是否有长度
	 * 
	 * @param str
	 * @return
	 */
	public static boolean hasLength(String str) {
		return (str != null && str.length() > 0);
	}

	/**
	 * 第一个字母变大写
	 * 
	 * @param str
	 * @return
	 */
	public static String capitalize(String str) {
		return changeFirstCharacterCase(str, true);
	}

	/**
	 * 第一个字母变小写
	 * 
	 * @param str
	 * @return
	 */
	public static String uncapitalize(String str) {
		return changeFirstCharacterCase(str, false);
	}

	private static String changeFirstCharacterCase(String str,
			boolean capitalize) {
		if (str == null || str.length() == 0) {
			return str;
		}
		StringBuffer buf = new StringBuffer(str.length());
		if (capitalize) {
			buf.append(Character.toUpperCase(str.charAt(0)));
		} else {
			buf.append(Character.toLowerCase(str.charAt(0)));
		}
		buf.append(str.substring(1));
		return buf.toString();
	}

	/**
	 * 比较 一个int值，是否包含在另一个int数组中 例： 3,{1,2,3,4,5} return true; 9,{1,2,3,4,5}
	 * return false;
	 * 
	 * @param compareValue 待比较的int
	 * @param intArray int数组
	 * @return
	 */
	public static boolean containValue(int compareValue, int[] intArray) {
		if (intArray == null)
			return false;
		for (int j = 0; j < intArray.length; j++)
			if (intArray[j] == compareValue)
				return true;
		return false;
	}

	/**
	 * 用 linkStr 将 strs 数组中各元素连接起来 例： 传入：{"a == a","b != b","c > d"}," or " 返回："
	 * a == a or b != b or c > d "
	 * 
	 * @param strs
	 * @param linkStr
	 * @return String
	 */
	public static String linkString(String[] strs, String linkStr) {
		if (null == strs || null == linkStr)
			return null;
		StringBuffer resultStrBuf = new StringBuffer();
		for (int i = 0; i < strs.length; i++) {
			if (strs[i] != null) {
				resultStrBuf.append(strs[i]);
				resultStrBuf.append(linkStr);
			}
		}
		String linkResult = resultStrBuf.toString();
		int removeLink = linkResult.length() - linkStr.length();
		return removeLink > 0 ? linkResult.substring(0, removeLink) : "";
	}

	/**
	 * 用 linkStr 将 strList List中各元素连接起来 例： 传入：{"a == a","b != b","c > d"}," or "
	 * 返回：" a == a or b != b or c > d "
	 * 
	 * @param strList
	 * @param linkStr
	 * @return String
	 */
	public static String linkString(List strList, String linkStr) {
		if (null == strList || null == linkStr)
			return null;

		StringBuffer resultStrBuf = new StringBuffer();
		Iterator it = strList.iterator();
		while (it.hasNext()) {
			Object obj = it.next();
			if (obj instanceof String) {
				resultStrBuf.append((String) obj);
				resultStrBuf.append(linkStr);
			}
			// else
			// 如非String实例，放弃该列表项;
			// 如需处理，可在此修改
		}
		String linkResult = resultStrBuf.toString();
		return linkResult.substring(0, linkResult.length() - linkStr.length());
	}

	/**
	 * str == null return true else return false
	 */
	public static boolean isNull(String str) {
		return str == null;
	}

	/**
	 * str == null && str.equals("") return true else return false
	 */
	public static boolean isEmpty(String str) {
		return (str == null || str.length() == 0);
	}

	/**
	 * return isEmpty( str.trim() )
	 */
	public static boolean isEmptyTrim(String str) {
		return str == null || isEmpty(str.trim());
	}

	public static boolean isNotNull(String str) {
		return !isNull(str);
	}

	public static boolean isNotEmpty(String str) {
		return !isEmpty(str);
	}

	public static boolean isNotEmptyTrim(String str) {
		return !isEmptyTrim(str);
	}

	/**
	 * 简单连接 link("aa","bb") == "aabb"
	 */
	public static String link(String str, String str2) {
		String[] strs = new String[2];
		strs[0] = str;
		strs[1] = str2;
		return linkByStringBuffer(strs);
	}

	/**
	 * 简单连接 link("aa","bb","cc") == "aabbcc"
	 */
	public static String link(String str, String str2, String str3) {
		String[] strs = new String[3];
		strs[0] = str;
		strs[1] = str2;
		strs[2] = str3;
		return linkByStringBuffer(strs);
	}

	/**
	 * 简单连接 link("aa","bb","cc","dd") == "aabbccdd"
	 */
	public static String link(String str, String str2, String str3, String str4) {
		String[] strs = new String[4];
		strs[0] = str;
		strs[1] = str2;
		strs[2] = str3;
		strs[3] = str4;
		return linkByStringBuffer(strs);
	}

	/**
	 * 简单连接 link("aa","bb","cc","dd","ee") == "aabbccddee"
	 */
	public static String link(String str, String str2, String str3,
			String str4, String str5) {
		String[] strs = new String[5];
		strs[0] = str;
		strs[1] = str2;
		strs[2] = str3;
		strs[3] = str4;
		strs[4] = str5;
		return linkByStringBuffer(strs);
	}

	/**
	 * 简单连接 linkByStringBuffer("aa"/"bb"/"cc"/"dd") ==
	 * link("aa","bb","cc","dd");
	 */
	public static String linkByStringBuffer(String[] strs) {
		StringBuffer sbf = new StringBuffer();
		for (int i = 0; strs != null && i < strs.length; i++) {
			if (!isEmpty(strs[i]))
				sbf.append(strs[i]);
		}

		return sbf.toString();
	}

	/**
	 * 封装MessageFormat.format()的调用 format(" aa {0} cc ","bb") == " aa bb cc "
	 */
	public static String format(String pattern, String str) {
		String[] arrStr = new String[1];
		arrStr[0] = str;
		return MessageFormat.format(pattern, arrStr);
	}

	/**
	 * 封装MessageFormat.format()的调用 format(" aa {0} cc {1} ","bb","dd") == " aa
	 * bb cc dd "
	 */
	public static String format(String pattern, String str, String str2) {
		String[] arrStr = new String[2];
		arrStr[0] = str;
		arrStr[1] = str2;
		return MessageFormat.format(pattern, arrStr);
	}

	/**
	 * 封装MessageFormat.format()的调用 format(" aa {0} cc {1} {2} ","bb","dd","ee") == "
	 * aa bb cc dd ee "
	 */
	public static String format(String pattern, String str, String str2,
			String str3) {
		String[] arrStr = new String[3];
		arrStr[0] = str;
		arrStr[1] = str2;
		arrStr[2] = str3;
		return MessageFormat.format(pattern, arrStr);
	}

	/**
	 * 封装MessageFormat.format()的调用 format(" aa {0} cc {1} {2} {3}
	 * ","bb","dd","ee","ff") == " aa bb cc dd ee ff "
	 */
	public static String format(String pattern, String str, String str2,
			String str3, String str4) {
		String[] arrStr = new String[4];
		arrStr[0] = str;
		arrStr[1] = str2;
		arrStr[2] = str3;
		arrStr[3] = str4;
		return MessageFormat.format(pattern, arrStr);
	}

	/**
	 * 封装MessageFormat.format()的调用 format(" aa {0} cc {1} {2} {3} {4}
	 * ","bb","dd","ee","ff","gg") == " aa bb cc dd ee ff gg "
	 */
	public static String format(String pattern, String str, String str2,
			String str3, String str4, String str5) {
		String[] arrStr = new String[5];
		arrStr[0] = str;
		arrStr[1] = str2;
		arrStr[2] = str3;
		arrStr[3] = str4;
		arrStr[4] = str5;
		return MessageFormat.format(pattern, arrStr);
	}

	/**
	 * 统计串str中匹配串sub的计数
	 * 
	 * @param str
	 * @param sub
	 * @return
	 */
	public static int countMatches(String str, String sub) {
		if (isEmpty(str) || isEmpty(sub))
			return 0;
		int count = 0;
		for (int idx = 0; (idx = str.indexOf(sub, idx)) != -1; idx += sub
				.length())
			count++;

		return count;
	}

	/**
	 * 将串str中匹配searchStr中任一字符的部分，全部替换为replaceStr
	 * 
	 * @param str
	 * @param searchStr
	 * @param replaceStr
	 * @return
	 */
	public static String replaceAny(String str, String searchStr,
			String replaceStr) {
		if (isEmpty(str) || isEmpty(searchStr))
			return str;
		if (replaceStr == null)
			replaceStr = "";
		boolean modified = false;
		StringBuffer buf = new StringBuffer(str.length());
		for (int i = 0; i < str.length(); i++) {
			char ch = str.charAt(i);
			int index = searchStr.indexOf(ch);
			if (index >= 0) {
				modified = true;
				if (index < replaceStr.length())
					buf.append(replaceStr.charAt(index));
			} else {
				buf.append(ch);
			}
		}

		if (modified)
			return buf.toString();
		else
			return str;
	}

	/**
	 * 将串str中匹配searchStr中任一字符的部分，全部替换为replaceStr
	 * 
	 * @param str
	 * @param searchStr
	 * @param replaceStr
	 * @return
	 */
	public static String replaceAny(String str, String searchStr[],
			String replaceStr) {
		String strNew = new String(str);
		for (int i = 0; i < searchStr.length; i++) {
			strNew = strNew
					.replaceAll(String.valueOf(searchStr[i]), replaceStr);
		}
		return strNew;
	}

	/**
	 * 将byte[]值直接转换为字符串，用逗号分隔。用于序列化对象
	 * 
	 * @param arrByte
	 * @return
	 */
	public static String toString(byte[] arrByte) {
		if (arrByte == null)
			return "";
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < arrByte.length; i++) {
			// System.out.println( arrByte[i]);
			buffer.append(arrByte[i] + ",");
		}
		return buffer.toString();
	}

	/**
	 * StringUtils.toString()的逆操作。用于反序列化对象
	 * 
	 * @param str
	 * @return
	 */
	public static byte[] toByteArray(String str) {
		if (str == null)
			return null;
		String[] arrStr = str.split(",");
		byte[] arrByte = new byte[arrStr.length];
		for (int i = 0; i < arrStr.length; i++) {
			arrByte[i] = Byte.parseByte(arrStr[i]);
		}
		return arrByte;
	}

	/**
	 * 字符串化存储对象。用于网络传输
	 * 
	 * @param object
	 * @return
	 * @throws AppException
	 */
	public static String toString(Object obj) throws AppException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ObjectOutputStream oos;
		String str = null;
		try {
			oos = new ObjectOutputStream(out);
			oos.writeObject(obj);
			str = toString(out.toByteArray());
			out.close();
			oos.close();
		} catch (IOException e) {
			throw new AppException("异步处理错误：" + e.getCause());
		}

		return str;
	}

	/**
	 * 反序列化对象，将字符串转为对象
	 * 
	 * @param str
	 * @return
	 * @throws AppException
	 */
	public static Object toObject(String str) throws AppException {

		Object obj = null;
		try {
			InputStream in = new ByteArrayInputStream(toByteArray(str));
			ObjectInputStream oin = new ObjectInputStream(in);
			obj = oin.readObject();
			in.close();
			oin.close();
		} catch (NullPointerException npe) {
			throw new AppException("异步处理错误：" + npe.getCause());
		} catch (IOException e) {
			throw new AppException("异步处理错误：" + e.getCause());
		} catch (ClassNotFoundException ce) {
			throw new AppException("异步处理错误：" + ce.getCause());
		}

		return obj;
	}

	/**
	 * 将字符串第一个字符转换成大写
	 * 
	 * @param str
	 * @return
	 */
	public static String toUpperCaseFirst(String str) {
		return str.substring(0, 1).toUpperCase() + str.substring(1);
	}

	/**
	 * 获取当前时间的 MMddHHmmss格式的整数
	 * 
	 * @return
	 */
	public static int getTime() {
		GregorianCalendar gc = new GregorianCalendar();
		int month = gc.get(GregorianCalendar.MONTH) + 1;
		int day = gc.get(GregorianCalendar.DAY_OF_MONTH);
		int hour = gc.get(GregorianCalendar.HOUR_OF_DAY);
		int mits = gc.get(GregorianCalendar.MINUTE);
		int secd = gc.get(GregorianCalendar.SECOND);

		int random = Integer.parseInt(format(month) + format(day)
				+ format(hour) + format(mits) + format(secd));
		return random;
	}

	/**
	 * 个位数，在前补零
	 * 
	 * @param i
	 * @return
	 */
	private static String format(int i) {
		return i < 10 ? "0" + i : "" + i;
	}

	// ******************add by liqiyi on 2007.6.27**************
	/**
	 * 判断一个字符串是否null或""或"null" 是 false 否 true
	 * 
	 * @param str
	 * @return
	 * @author 袁金锋
	 */
	public static boolean isBlank(String str) {
		if (str == null || str.length() == 0 || "null".equals(str.trim())) {
			return false;
		}
		return true;
	}

	/**
	 * 判断字符串是否为空
	 * 
	 * @param e
	 * @return
	 */
	static public boolean empty(String e) {
		return e == null || e.length() == 0;
	}

	/**
	 * 字符串删除前后的空白字符后的长度是否为0
	 * 
	 * @param e
	 * @return
	 */
	static public boolean emptyTrimed(String e) {
		return e == null || e.trim().length() == 0;
	}

	/**
	 * 字符串删除前后的空白字符后的长度是否不为0
	 * 
	 * @param e
	 * @return
	 */
	static public boolean notEmptyTrimed(String e) {
		return !emptyTrimed(e);
	}

	/**
	 * 比较两个字符串是否相等,
	 * 
	 * @param s1
	 * @param s2
	 * @return
	 */
	static public boolean equals(String s1, String s2) {
		if (s1 == null) {
			return s2 == null;
		}

		return s1.equals(s2);
	}

	/**
	 * 比较两个删除两端空白字符的字符串是否相等,
	 * 
	 * @param s1
	 * @param s2
	 * @return
	 */
	static public boolean equalsTrimed(String s1, String s2) {
		if (s1 == null) {
			return s2 == null;
		} else {
			if (s2 == null) {
				return false;
			} else {
				return s1.trim().equals(s2.trim());
			}
		}
	}

	/**
	 * 判断字符串是否不为空
	 * 
	 * @param e
	 * @return
	 */
	static public boolean notEmpty(String e) {
		return !empty(e);
	}

	/**
	 * 把字符串的第一个字符变为大写
	 * 
	 * @param str
	 * @return
	 */
	public static String toUpperCase(String str) {
		if (empty(str)) {
			return null;
		}
		if (str.length() == 1) {
			return str.toUpperCase();
		}
		return Character.toUpperCase(str.charAt(0)) + str.substring(1);
	}

	/**
	 * 将字符串的HMTL特殊字符转换成页面可以显示的内容
	 * 
	 * @param text
	 * @return
	 */
	public static String text2html(String text) {
		if (text == null)
			return null;
		String[] se = { "<", ">", "(\r\n|\n\r|\n|\r)", "\t", "  " };
		String[] rp = { "&lt;", "&gt;", "\n<br>", "&nbsp;&nbsp;&nbsp;&nbsp;",
				"&nbsp; " };
		for (int i = 0; i < se.length; i++) {
			text = text.replaceAll(se[i], rp[i]);
		}
		return text;
	}

	/**
	 * 将换行符或回车符转成html的换行特殊符号
	 * 
	 * @param text
	 * @return
	 */
	public static String ln2br(String text) {
		if (text == null)
			return null;
		return text.replaceAll("(\r\n|\n\r|\n|\r)", "\n<br>");
	}

	public static String[] tokenSplit(String source, String delim) {
		return tokenSplit(source, delim, false);
	}

	public static String[] tokenSplit(String source, String delim,
			boolean returnDelim) {
		StringTokenizer st = new StringTokenizer(source, delim, returnDelim);
		String[] r = new String[st.countTokens()];
		for (int i = 0; st.hasMoreTokens(); i++) {
			r[i] = st.nextToken();
		}
		return r;
	}

	/**
	 * 剪掉字符串前面的空格和后面的空格
	 * 
	 * @param str
	 * @return
	 */
	public static String trim(String str) {
		return str == null ? null : str.trim();
	}

	/**
	 * 类似javascript的用法 <br>
	 * 传入的内容,等于str.replace(reg,replacement)中的str <br>
	 * 如果不能match,返回原来的字符串<br>
	 * <code>
	 *   text = "www.263.com www.163.com";
	 *   reg = "www\\.([^\\.]*\\.com)";
	 *   replacement = "www.$1.com.cn";
	 *
	 *   StringUtil.regexpReplace(text,reg,replacement);
	 *
	 *   result : www.263.com.cn www.163.com.cn
	 * </code>
	 * 
	 * @param text 传入的内容,等于上面例子中的str
	 * @param regexp
	 * @param replacement
	 * @return
	 */
	public static String regexpReplace(String text, String regexp,
			String replacement) {

		if (text == null || regexp == null || regexp == null) {
			return null;
		}

		StringBuffer sb = new StringBuffer();

		Pattern p = null;
		p = Pattern.compile(regexp);

		Matcher m = p.matcher(text);
		boolean result = m.find();
		if (result == false) {
			return text;
		}

		while (result) {
			m.appendReplacement(sb, replacement);
			result = m.find();
		}

		return sb.toString();
	}

	/**
	 * 是否包含中文
	 * 
	 * @param word
	 * @return
	 */
	public static boolean isContainChinese(String word) {
		Pattern pa = Pattern.compile(".*[\u4E00-\u9FA5].*", Pattern.CANON_EQ);
		return pa.matcher(word).matches();
	}

	/**
	 * 转换字符的编码
	 * 
	 * @param text
	 * @param srcEncoding 原编码
	 * @param destEncoding 目标编码
	 * @return
	 */
	public static String changeEncoding(String text, String srcEncoding,
			String destEncoding) {
		if (text == null) {
			return null;
		}
		byte[] bs = null;
		try {
			bs = text.getBytes(srcEncoding);
			return new String(bs, destEncoding);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 汉字转拼音

	 * 
	 * @param sCN String 汉字字符串

	 * @return String 拼音首字母

	 */
//	public static String getCn2Spell(String sCN) {
//		if (sCN == null | sCN.toCharArray().length==0) {
//			return "";
//		}
//		StringBuilder ret = new StringBuilder("");
//		for(char s : sCN.toCharArray()){
//			ret.append(getPinyinFirst(s));
//		}
//		return ret.toString();
//	}
//	private static String getPinyinFirst(char chr){
//		try {
//			HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
//			format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
//			format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
//			String[] hanyuPinyinStringArray = PinyinHelper.toHanyuPinyinStringArray(chr,format);
//			if(CollectionUtils.empty(hanyuPinyinStringArray)){
//				return String.valueOf(chr);
//			}
//			String s = hanyuPinyinStringArray[0];
//			if(s == null || s.length() == 0){
//				return String.valueOf(chr);
//			}
//			return s.substring(0,1);
//		} catch (BadHanyuPinyinOutputFormatCombination e) {
//			return String.valueOf(chr);
//		}
//	}
	public static void main(String[] args) {
		System.out.println(indexOfTimes("abacadae", "a", 3));
	}

	/**
	 * 如何value为空或null,就返回defaultValue
	 * 
	 * @param value
	 * @param defaultValue 默认
	 * @return
	 */
	public static String formatParam(String value, String defaultValue) {
		String newValue = null;
		if ("".equals(value)) {
			newValue = null;
		} else if ("null".equals(value)) {
			newValue = defaultValue;
		} else {
			newValue = value;
		}
		return newValue;
	}

	/**
	 * 取得字符串的右多少位
	 * 
	 * @param value
	 * @param count
	 * @return
	 */
	public static String getStringFromRight(String value, int count) {
		int valueLen = value.length();
		if (valueLen <= count) {
			return value;
		} else {
			return value.substring(valueLen - count);
		}
	}

	/**
	 * 字符串比较取最小的
	 * 
	 * @param method1
	 * @param method2
	 * @return String
	 */
	public static String min(String method1, String method2) {
		if (method1 != null && method2 != null) {
			return method1.compareTo(method2) > 0 ? method2 : method1;
		} else if (method1 != null && method2 == null) {
			return method1;
		} else if (method1 == null && method2 != null) {
			return method2;
		} else {
			return null;
		}
	}
	
	/**
	 * 字符串比较取最大的
	 * 
	 * @param method1
	 * @param method2
	 * @return String
	 */
	public static String max(String method1, String method2) {
		if (method1 != null && method2 != null) {
			return method1.compareTo(method2) > 0 ? method1 : method2;
		} else if (method1 != null && method2 == null) {
			return method1;
		} else if (method1 == null && method2 != null) {
			return method2;
		} else {
			return null;
		}
	}
	public static String toISO8859_1(String in) {
		return toISO8859_1(in,"GBK");
	}
	
	public static String toISO8859_1(String in,String fromEncoding) {
		String strOut = null;
		if (in == null || in.trim().equals("")) {
			return in;
		}
		try {
			byte b[] = in.getBytes(fromEncoding);
			strOut = new String(b, "ISO8859_1");
		} catch (UnsupportedEncodingException unsupportedencodingexception) {
		}
		return strOut;
	}
}